<template>
  <div class="cart-container">
    <van-nav-bar title="购物车" right-text="删除" left-arrow @click-left="onClickLeft" @click-right="onClickRight"
      v-if="isdel" />
    <van-nav-bar title="购物车" left-arrow @click-left="onClickLeft" v-else />
    <div class="cart-list" v-for="item in cartList" @click="goDetail(item.pid)">
      <!-- 商品列表 -->
      <van-swipe-cell style="position: relative; margin-left: 10px;">
        <van-checkbox-group v-model="checkedResult" @change="checkedResultChange"
          style="position: absolute; z-index: 1; left: 2px; top: 50%; transform: translateY(-50%);">
          <van-checkbox :name="item.id" @click.stop="handleCheckboxClick"></van-checkbox>
          <!-- <van-checkbox name="b"></van-checkbox> -->
        </van-checkbox-group>
        <!-- <van-checkbox v-model="checked" @click="check(item.id)"
          style="position: absolute; z-index: 1; left: 2px; top: 50%; transform: translateY(-50%);"></van-checkbox> -->
        <van-stepper class="bengjingqi" v-model="item.num" min="1" max="100" integer
          @click.stop="bujinqi(item.pid, item.num)" />
        <van-card :num="item.num" :price="item.price" :desc="item.product.content" :title="item.name" class="goods-card"
          :thumb="item.product.shopUrl_text" />
        <template #right>
          <van-button square text="删除" @click="delCart(item.id)" type="danger" class="delete-button" />
        </template>
      </van-swipe-cell>




    </div>
    <!-- 空购物车状态 -->
    <!-- <div class="empty-cart" v-if="cartList.length === 0">
      <img src="https://picsum.photos/seed/empty/200/200" alt="空购物车" class="empty-image">
      <p class="empty-text">购物车是空的</p>
      <button class="back-to-shopping" @click="backToShopping">返回购物</button>
    </div> -->
    <van-empty v-if="cartList.length==0" description="购物车是空的" />

    <!-- 为固定底部区域留出空间 -->
    <div class="cart-summary-spacer" style="background-color: #f8f8f8 !important;"></div>
  </div>

  <!-- 结算区域 -->
  <!-- <div class="cart-summary-fixed"> -->
  <!-- <van-submit-bar style="bottom: 50px !important; max-width: 512px;" disabled :price="price" button-text="提交订单" tip-icon="info-o" @submit="unSubmit" v-if="price==0"/> -->
  <van-submit-bar style="bottom: 50px !important; max-width: 512px;" :price="price" button-text="提交订单"
    @submit="onSubmit">
    <van-checkbox v-model="isCheckAll" @click="checkAllChange">全选</van-checkbox>
    <!-- <template #tip>
      你的收货地址不支持配送, <span @click="onClickLink" style="color: #1989fa;">修改地址</span>
    </template> -->
  </van-submit-bar>

  <!-- <div class="summary-left">
      <div class="select-all">
        <input type="checkbox" id="selectAll" v-model="isAllSelected" @change="toggleSelectAll"
          style="margin-top: 0px !important;">
        <label for="selectAll">全选</label>
      </div>
      <div class="summary-item">
        总价：<span class="total-price">¥ {{ totalPrice.toFixed(2) }}</span>
      </div>
    </div>
    <button class="checkout-btn" :disabled="!hasSelected">去结算({{ selectedCount }})</button> -->
  <!-- 回到顶部 -->
  <!-- <van-cell v-for="item in list" :key="item" :title="item" /> -->

  <!-- </div> -->
  <!-- 为固定底部区域留出空间 -->
  <div class="cart-summary-spacer" style="background-color: #f8f8f8 !important;"></div>
  <!-- 底部导航 -->
  <div class="footerBox">
    <Tab :modelValue="currentTab" @update:modelValue="handleTabUpdate"></Tab>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { showSuccessToast, showFailToast } from 'vant';
import { showConfirmDialog, showToast } from 'vant';
import Tab from './comm/Tab.vue';
import { POST } from '../services/request.js'
import { useRouter } from "vue-router";
const router = useRouter();
// 父传子，传递到子路由
const currentTab = ref('cart'); // 当前选中的标签页
const handleTabUpdate = (newValue) => {
  currentTab.value = newValue; // 更新父组件的状态
};

// 步进器的值
const value = ref(0.0);



// const onClickLink = () => showToast('修改地址');

const price = ref(0);

const isdel = ref(false);
// const sumprice = ref(null);

// 全选
// const checked = ref(false);
//多选
// const checked1 = ref(false);

// 获取用户的数据
const userData = ref([]);
// 定义用户id
const uid = ref('');

userData.value = JSON.parse(localStorage.getItem('LoginUser'));
// console.log(userData.value.id);
// 获取用户id
uid.value = userData.value.id;

// 存放购物车列表
const cartList = ref([]);
// 相同商品的数量
const pidCartNum = ref([]);

// 存商品提交订单的商品id
const prdId = ref([]);

const isCheckAll = ref(false);
const checkedResult = ref([]);
const list = ref([]);

onMounted(async () => {
  await getCartList();
})

// 全选
const checkAllChange = () => {
  if (isCheckAll.value) {
    checkedResult.value = list.value
    isdel.value = true;
  } else {
    checkedResult.value = []
    // price.value = 0.00
    isdel.value = false;
  }
  updateTotalPrice();
}

// 更新总价
const updateTotalPrice = () => {
  let total = 0;

  // 遍历购物车列表，累加选中商品的价格
  cartList.value.forEach(item => {
    if (checkedResult.value.includes(item.id)) {
      // 将价格和数量转为数字类型后计算
      const singlePrice = parseFloat(item.price);
      const num = parseInt(item.num);
      // 按分钱计算
      total += singlePrice * num * 100;
    }
  });

  // 更新总价（保留两位小数）
  price.value = parseFloat(total.toFixed(2));
}


// 单选的功能，然后怎么获取价格
const checkedResultChange = (value) => {
  const checkedCount = value.length
  isCheckAll.value = checkedCount === list.value.length
  updateTotalPrice();

  // 删除栏
  value.length === 0 ? isdel.value = false : isdel.value = true
}

// 查询购物车表
const getCartList = async () => {
  const cartListRes = await POST({
    url: '/Detail/getCart',
    params: {
      uid: uid.value
    }
  });
  if (cartListRes.code === 1) {
    console.log(cartListRes.data, '222222');
    pidCartNum.value = cartListRes.data.pdDataCount;
    // console.log(pidCartNum.value.total);
    cartList.value = cartListRes.data.cartList;


    // console.log(prdId.value,'999999');

    // console.log([...cartList.value]);
    // const product = [...cartList.value];    
    // console.log(cartList.value);

    // cartList.value.forEach(item=>{
    //   // console.log(item.price);
    //   // console.log(item.num);
    //   let singlePrice = item.price;
    //   let num = item.num;
    //   price.value += singlePrice * num *100;
    // })

    // console.log(price.value);
    // console.log(parseFloat(price.value));
    cartList.value.forEach(item => {
      list.value.push(item.id);
    });
  }
}
// 禁用状态点击
// const unSubmit = async()=>showToast('请选择需要购买的订单');

// 提交订单
const onSubmit = async () => {
  if (price.value > 0) {
    router.push({
      path: 'settlement',
      query: {
        ids: checkedResult.value,
        price: price.value,
        isStatic: 2
      }
    });
    // console.log();

  } else {
    // console.log();
    showToast('请选择需要购买的订单')
  }
};

// 返回
const onClickLeft = () => history.back();

// 右侧删除事件
const onClickRight = async () => {
  // batchDel();
  showConfirmDialog({
    title: '是否删除选中的购物车',
  })
    .then(() => {
      // on confirm 确认就删除
      batchDel();
    })
    .catch(() => {
      // on cancel 取消就不执行操作
    });
};



// 步进器
const bujinqi = async (pid, num) => {
  // console.log(pid,num);
  const updateCartNumRes = await POST({
    url: '/Cart/cartNum',
    params: {
      pid,
      num,
      uid: uid.value
    }
  })
  // 如果更新成功，重新计算总价
  if (updateCartNumRes.code === 1) {
    updateTotalPrice();
  }
}

// 删除
const delCart = async (id) => {
  // console.log(id);
  const delCartRes = await POST({
    url: '/Cart/delCart',
    params: {
      id
    }
  })
  if (delCartRes.code === 1) {
    showSuccessToast(delCartRes.msg);
    getCartList();
    updateTotalPrice();
  }
}

// 批量删除
const batchDel = async () => {
  const delIds = JSON.stringify(checkedResult.value)
  // console.log(delIds);
  const batchDelRes = await POST({
    url: '/Cart/batchDelCart',
    params: {
      delIds: delIds
    }
  })
  if (batchDelRes.code === 1) {
    showSuccessToast(batchDelRes.msg);
    // 清空选中状态
    checkedResult.value = [];
    isCheckAll.value = false;
    isdel.value = false;

    // 更新总价（此时总价应为0，因为没有选中项）
    updateTotalPrice();

    // 刷新购物车列表
    await getCartList();
  }
}

// 点击后跳入商品详情页
const goDetail = async (id) => {
  await router.push({
    name: 'detail',
    params: {
      id
    }
  })
}

// 阻止事件冒泡
const handleCheckboxClick = (e) => {
  e.stopPropagation();
};

// const onSubmit = () => showToast('点击按钮')
// const onClickLink = () => showToast('修改地址')



</script>

<style scoped>
.goods-card {
  margin-left: 10px;
  margin-right: 10px;
  background-color: white;
  border-bottom: 1px solid #e5e7ea;
  position: relative;
}

.delete-button {
  height: 100%;
}

.bengjingqi {
  /* position: absolute; */
  /* right: 10px; */
  position: absolute;
  z-index: 1;
  right: 20px;
  top: 50%;
  /* 顶部对齐父元素中心 */
  transform: translateY(-50%);
  /* 向上移动自身高度的50% */
}
</style>